import React from 'react';
import { 
  Upload, 
  Button, 
  Typography,
  Alert,
  Space,
  message,
  Progress,
  Card,
  InputNumber,
  Radio
} from 'antd';
import { 
  LoadingOutlined,
  InboxOutlined,
  DeleteOutlined,
  ScissorOutlined,
  DownloadOutlined
} from '@ant-design/icons';
import { pdfService } from '../services/pdfService';
import type { UploadProps } from 'antd';
import styles from './PDFSplitter.module.css';
import PageHeader from './PageHeader';

const { Dragger } = Upload;
const { Title, Text } = Typography;

type SplitMode = 'pages' | 'size';

const PDFSplitter: React.FC = () => {
  const [selectedFile, setSelectedFile] = React.useState<File | null>(null);
  const [splitting, setSplitting] = React.useState(false);
  const [error, setError] = React.useState<string>('');
  const [progress, setProgress] = React.useState(0);
  const [splitMode, setSplitMode] = React.useState<SplitMode>('pages');
  const [pageCount, setPageCount] = React.useState<number>(1);
  const [splitResult, setSplitResult] = React.useState<{
    blobs: Blob[];
    fileNames: string[];
  } | null>(null);

  const handleFileSelect = (info: any) => {
    const file = info.file;
    if (!file) return;

    setError('');
    setProgress(0);
    setSplitResult(null);

    if (!pdfService.validatePDFFile(file)) {
      setError('请上传有效的PDF文件（小于50MB）');
      return;
    }

    setSelectedFile(file);
  };

  const handleSplit = async () => {
    if (!selectedFile) {
      message.warning('请先选择PDF文件');
      return;
    }

    try {
      setSplitting(true);
      setError('');
      setProgress(0);
      setSplitResult(null);
      
      const response = await pdfService.splitPDF(selectedFile, {
        mode: splitMode,
        value: pageCount
      });
      
      if (response.code === 200 && response.data?.blobs && response.data?.fileNames) {
        setProgress(100);
        setSplitResult({
          blobs: response.data.blobs,
          fileNames: response.data.fileNames
        });
        message.success('分割成功！');
      } else {
        throw new Error('分割失败，请重试');
      }
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '分割过程出错';
      setError(errorMessage);
      message.error('分割失败：' + errorMessage);
    } finally {
      setSplitting(false);
    }
  };

  const handleDownload = async (blob: Blob, fileName: string) => {
    const hide = message.loading('准备保存...', 0);
    
    try {
      const success = await pdfService.saveFileWithDialog(blob, fileName);

      hide();
      
      if (success) {
        message.success('文件保存成功');
      } else {
        message.info('已取消保存');
      }
    } catch (error) {
      hide();
      message.error('文件保存失败，请重试');
      console.error('Download error:', error);
    }
  };

  const uploadProps: UploadProps = {
    name: 'file',
    multiple: false,
    accept: '.pdf',
    showUploadList: false,
    beforeUpload: () => false,
    onChange: handleFileSelect,
  };

  return (
    <div className={styles.container}>
      <PageHeader title="分割PDF" />
      <Card className={styles.splitterCard}>
        <Title level={4} className={styles.cardTitle}>
          PDF文件分割
        </Title>

        <div className={styles.uploadSection}>
          {!selectedFile ? (
            <Dragger {...uploadProps} className={styles.draggerContainer}>
              <p className="ant-upload-drag-icon">
                <InboxOutlined className={styles.uploadIcon} />
              </p>
              <p className={styles.uploadText}>
                点击或拖拽PDF文件到此区域
              </p>
              <p className={styles.uploadHint}>
                支持单个PDF文件，大小不超过50MB
              </p>
            </Dragger>
          ) : (
            <div className={styles.fileInfo}>
              <div className={styles.fileDetails}>
                <span className={styles.fileName}>{selectedFile.name}</span>
                <span className={styles.fileSize}>
                  {(selectedFile.size / (1024 * 1024)).toFixed(2)}MB
                </span>
              </div>
              <Space>
                <Button 
                  icon={<DeleteOutlined />}
                  onClick={() => {
                    setSelectedFile(null);
                    setError('');
                    setProgress(0);
                    setSplitResult(null);
                  }}
                >
                  删除
                </Button>
              </Space>
            </div>
          )}
        </div>

        {selectedFile && (
          <div className={styles.splitOptions}>
            <Radio.Group 
              value={splitMode}
              onChange={(e) => setSplitMode(e.target.value)}
              className={styles.modeSelect}
            >
              <Radio.Button value="pages">按页数分割</Radio.Button>
              <Radio.Button value="size">按大小分割</Radio.Button>
            </Radio.Group>

            <div className={styles.valueInput}>
              <InputNumber
                min={1}
                value={pageCount}
                onChange={(value) => setPageCount(value || 1)}
                addonAfter={splitMode === 'pages' ? '页/文件' : 'MB/文件'}
              />
            </div>

            <Button
              type="primary"
              icon={splitting ? <LoadingOutlined /> : <ScissorOutlined />}
              onClick={handleSplit}
              loading={splitting}
              disabled={!!error}
            >
              {splitting ? '分割中...' : '开始分割'}
            </Button>
          </div>
        )}

        {error && (
          <Alert
            message="错误"
            description={error}
            type="error"
            showIcon
            className={styles.alert}
          />
        )}

        {splitting && (
          <div className={styles.progressContainer}>
            <Progress 
              percent={progress} 
              status={progress === 100 ? "success" : "active"}
              strokeColor={{
                '0%': '#108ee9',
                '100%': '#87d068',
              }}
            />
          </div>
        )}

        {splitResult && (
          <div className={styles.resultList}>
            <Title level={5}>分割结果：</Title>
            {splitResult.blobs.map((blob, index) => (
              <div key={index} className={styles.resultItem}>
                <Text>{splitResult.fileNames[index]}</Text>
                <Button 
                  type="link"
                  icon={<DownloadOutlined />}
                  onClick={() => handleDownload(blob, splitResult.fileNames[index])}
                >
                  保存
                </Button>
              </div>
            ))}
          </div>
        )}
      </Card>
    </div>
  );
};

export default PDFSplitter; 